package com.syni.mdd.yhd.common.all.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.syni.mdd.yhd.common.all.entity.cdn.BmsCdnData;
import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
@Log4j2
public class CDNUtils {

    private static long appId = 1251624226;
    private static String secretId = "AKIDWs1xfAxWN0PcfV5WhePwFKCqGSRCO4B5";
    private static String secretKey = "mLgojRvCG6i7IFzVnriLkvtd9RWN6btx";
    //private static String secretId = "AKID792lYCElhS3XqzTiBTq00viNUWQDRY0H";
    //private static String secretKey = "FLn4CB6qS3YwJctBLK8oKApKeoncHzSp";
    public static String bucketName = "dsp";
    public static final int width = 200;
    public static final int height = 200;

/*    public static void main(String[] args) {
        BmsCdnData b = uploadCOS(bucketName, "/material/", "/project/aa.png", 100, 100);
        System.err.print(b);
//        deleteCOS(bucketName,"/information/a3a1928bf508460fb8a4ea7c7dd5e0a0.png");
    }*/

    /**
     * @param bucketName (台风：typhoon,短视频：dsp)
     * @param cosPath    上传图片位置文件夹
     * @param loaclPath  本地图片地址
     * @param sWidth     压缩图宽
     * @param sHeight    压缩图高
     * @return
     */
    public static BmsCdnData uploadCOS(String bucketName, String cosPath, String loaclPath, int sWidth, int sHeight) {
        BmsCdnData cdnData = null;
        COSClient cosClient = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

            // 1 初始化用户身份信息（secretId, secretKey）。
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
            Region region = new Region("ap-guangzhou");
            ClientConfig clientConfig = new ClientConfig(region);
            // 3 生成 cos 客户端。
            cosClient = new COSClient(cred, clientConfig);
            String suffix = "." + loaclPath.substring(loaclPath.lastIndexOf(".") + 1);
            String imageName = sdf.format(new Date()) + getStringRandom(4);
            String bigImageName = "b" + imageName + suffix;
            String smallImageName =  "b" + imageName + "_s" + suffix;
            String bigImageResult = upload(bucketName + "-" + appId, cosPath + bigImageName, loaclPath, cosClient);
            System.out.println("localPath: " + loaclPath);
            System.out.println("smallImage：" + smallImageName);
            String smallPath = compressByScan(loaclPath, smallImageName,0.5d);
            String smallImageResult = "";
            if(StringUtils.isNotBlank(smallPath)) {
                smallImageResult = upload(bucketName + "-" + appId, cosPath + smallImageName, smallPath, cosClient);
            }
            if (StringUtils.isNotBlank(bigImageResult)) {
                //System.err.print("上传成功原图url------>>>>" + bigImageResult);
                //System.err.print("上传成功缩略图url------>>>>" + smallImageResult);
                cdnData = new BmsCdnData();
                cdnData.setCosPath(cosPath);
                cdnData.setSourceUrlBig(bigImageResult);
                cdnData.setSourceUrlSmall(smallImageResult);
            }
        } catch (Exception e) {
            log.error("upload error",e);
            log.error(e.getMessage(),e);
        } finally {
            cosClient.shutdown();
        }
        return cdnData;
    }


    /**
     * @param bucketName (台风：typhoon,短视频：dsp)
     * @param cosPath    上传图片位置文件夹
     * @param loaclPath  本地图片地址
     * @param scale     压缩比例
     * @return
     */
    public static BmsCdnData uploadCOS(String bucketName, String cosPath, String loaclPath,Double scale) {
        BmsCdnData cdnData = null;
        COSClient cosClient = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

            // 1 初始化用户身份信息（secretId, secretKey）。
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
            Region region = new Region("ap-guangzhou");
            ClientConfig clientConfig = new ClientConfig(region);
            // 3 生成 cos 客户端。
            cosClient = new COSClient(cred, clientConfig);
            String suffix = "." + loaclPath.substring(loaclPath.lastIndexOf(".") + 1);
            String imageName = sdf.format(new Date()) + getStringRandom(4);
            String bigImageName = "b" + imageName + suffix;
            String smallImageName =  "b" + imageName + "_s" + suffix;
            String bigImageResult = upload(bucketName + "-" + appId, cosPath + bigImageName, loaclPath, cosClient);
            System.out.println("localPath: " + loaclPath);
            System.out.println("smallImage：" + smallImageName);
            String smallPath = compressByScan(loaclPath, smallImageName,scale);
            String smallImageResult = "";
            if(StringUtils.isNotBlank(smallPath)) {
                smallImageResult = upload(bucketName + "-" + appId, cosPath + smallImageName, smallPath, cosClient);
            }
            if (StringUtils.isNotBlank(bigImageResult)) {
                //System.err.print("上传成功原图url------>>>>" + bigImageResult);
                //System.err.print("上传成功缩略图url------>>>>" + smallImageResult);
                cdnData = new BmsCdnData();
                cdnData.setCosPath(cosPath);
                cdnData.setSourceUrlBig(bigImageResult);
                cdnData.setSourceUrlSmall(smallImageResult);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            cosClient.shutdown();
        }
        return cdnData;
    }

    public static void deleteCOS(String bucketName, String cosPath) {
      /*  DelFileRequest delFileRequest = new DelFileRequest(bucketName, cosPath);
        // 初始化密钥信息
        Credentials cred = new Credentials(appId, secretId, secretKey);
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        // 设置bucket所在的区域，比如华南园区：gz； 华北园区：tj；华东园区：sh ；
        clientConfig.setRegion("gz");
        // 初始化cosClient
        COSClient cosClient = new COSClient(clientConfig, cred);
        String delFileRet = cosClient.delFile(delFileRequest);
        JSONObject jsonObject = JSONObject.parseObject(delFileRet);
        String code = jsonObject.getString("code");*/
//        JSONObject data = jsonObject.getJSONObject("data");
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-guangzhou");
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        cosClient.deleteObject(bucketName + "-" + appId, cosPath);
        cosClient.shutdown();
    }

  
    /**
     * @Description 随机生成带数字和字母的数字随机数
     * @Author: cfx
     * @Date: 2019/7/3
     */
    public static String getStringRandom(int length) {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val.append((char)(random.nextInt(26) + temp));
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val.append(String.valueOf(random.nextInt(10)));
            }
        }
        return val.toString();
    }


    public static String compress(String localPath, String fileName, int width, int height) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateFile = sdf.format(new Date());
        File file = new File(localPath);
        File parentFile = file.getParentFile();
        String imgPath = parentFile.getAbsolutePath() + "/" + fileName;
        /*try {
            Thumbnails.of(localPath).size(width, height).toFile(imgPath);
            return imgPath;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }*/
        return null;
    }

    public static String compressByScan(String localPath, String fileName,Double scale) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateFile = sdf.format(new Date());
        File file = new File(localPath);
        File parentFile = file.getParentFile();
        String imgPath = parentFile.getAbsolutePath() + "/" + fileName;
        try {
            Thumbnails.of(localPath).scale(scale).toFile(imgPath);
            return imgPath;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public static String upload(String bucketName, String cosPath, String localPath, COSClient cosClient) {
        // 指定要上传的文件
        File localFile = new File(localPath);
        // 指定要上传到 COS 上对象键
        String key = cosPath;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        String eTag = putObjectResult.getETag();
        if (null != eTag && !"".equals(eTag)) {
            //System.out.println(String.format("http://%s.cos.ap-guangzhou.myqcloud.com/%s",bucketName,key));
            //String url = "http://dsp.syni.com" + cosPath;
            String url = String.format("http://%s.cos.ap-guangzhou.myqcloud.com%s",bucketName,key);
            return url;
        }
        return "";
    }


    public static void down(){
        try{
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            ClientConfig clientConfig = new ClientConfig();
            Region region = new Region("ap-guangzhou");
            clientConfig.setRegion(region);

            COSClient cosClient = new COSClient(cred, clientConfig);
            // 指定对象所在的存储桶
            String bucketName = "dsp-1251624226";
            // 指定对象在 COS 上的对象键
            String key = "flowb201911211527498058X2b.pdf";
            // 指定要下载到的本地路径
            File downFile = new File("D:/setting/img/a.pdf");
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
            System.out.println(downObjectMeta);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }

    public static void uploadTwo(String localPath){
        COSClient cosClient = null;
        try {
            String appId = "1253327941";
            String secretId = "AKIDWs1xfAxWN0PcfV5WhePwFKCqGSRCO4B5";
            String secretKey = "mLgojRvCG6i7IFzVnriLkvtd9RWN6btx";
            COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
            Region region = new Region("ap-guangzhou");
            ClientConfig clientConfig = new ClientConfig(region);
            cosClient = new COSClient(cred, clientConfig);

           /* CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
            // 设置 bucket 的权限为 PublicRead(公有读私有写), 其他可选有私有读写, 公有读写
            createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);*/

            // 指定要上传的文件
            File localFile = new File(localPath);
            // 指定要上传到的存储桶
            String bucketName = "dsp-1253327941";
            // 指定要上传到 COS 上对象键
            String key = "logo/qps3.png";
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println(putObjectResult);
            System.out.println(String.format("http://%s.cos.ap-guangzhou.myqcloud.com/%s",bucketName,key));
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }finally {
            if(cosClient != null) {
                cosClient.shutdown();
            }
        }
    }

}
